{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:35:56.628130Z",
     "start_time": "2019-03-20T09:35:45.661384Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\Anaconda3\\lib\\requests\\__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.11) or chardet (3.0.4) doesn't match a supported version!\n",
      "  RequestsDependencyWarning)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0\n",
      "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n",
      "data loading ...\n",
      "data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n"
     ]
    }
   ],
   "source": [
    "%run init.ipynb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:35:56.633000Z",
     "start_time": "2019-03-20T09:35:56.630450Z"
    },
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "preprocessor = mz.preprocessors.BasicPreprocessor(\n",
    "    truncated_length_left = 10,\n",
    "    truncated_length_right = 40,\n",
    "    filter_low_freq = 2\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.249211Z",
     "start_time": "2019-03-20T09:35:56.634788Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval:   0%| | 0/94 [00:00<?, ?it/s]Building prefix dict from the default dictionary ...\n",
      "Loading model from cache C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 1.595 seconds.\n",
      "Prefix dict has been built successfully.\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 94/94 [00:02<00:00, 39.50it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 99/99 [00:00<00:00, 131.20it/s]\n",
      "Processing text_right with append: 100%|████████████████████████████████████████████| 99/99 [00:00<00:00, 49515.39it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|████████████████████████████████████| 99/99 [00:00<00:00, 33165.82it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 16510.38it/s]\n",
      "Processing text_left with extend: 100%|█████████████████████████████████████████████| 94/94 [00:00<00:00, 11765.58it/s]\n",
      "Processing text_right with extend: 100%|████████████████████████████████████████████| 99/99 [00:00<00:00, 49515.39it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████████████████████████████████| 750/750 [00:00<00:00, 749161.23it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 94/94 [00:00<00:00, 129.91it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 99/99 [00:00<00:00, 157.99it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 49533.11it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 94/94 [00:00<00:00, 31345.57it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 33018.14it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 94/94 [00:00<00:00, 15657.85it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 19785.40it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 94/94 [00:00<00:00, 18805.85it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 99/99 [00:00<00:00, 49610.05it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 49/49 [00:00<00:00, 172.03it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 49/49 [00:00<00:00, 167.91it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 49/49 [00:00<00:00, 24560.34it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 49/49 [00:00<00:00, 16329.33it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 49/49 [00:00<00:00, 24554.47it/s]\n",
      "Processing text_left with transform: 100%|███████████████████████████████████████████| 49/49 [00:00<00:00, 6130.38it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 49/49 [00:00<00:00, 24539.81it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 49/49 [00:00<00:00, 24510.54it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 49/49 [00:00<00:00, 24466.77it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 29/29 [00:00<00:00, 117.95it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 30/30 [00:00<00:00, 176.57it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 15017.20it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 29/29 [00:00<00:00, 29036.72it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 29995.02it/s]\n",
      "Processing text_left with transform: 100%|███████████████████████████████████████████| 29/29 [00:00<00:00, 9664.29it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 30023.65it/s]\n",
      "Processing length_left with len: 100%|███████████████████████████████████████████████| 29/29 [00:00<00:00, 7239.74it/s]\n",
      "Processing length_right with len: 100%|██████████████████████████████████████████████| 30/30 [00:00<00:00, 3335.34it/s]\n"
     ]
    }
   ],
   "source": [
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)\n",
    "test_pack_processed = preprocessor.transform(test_pack_raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.262937Z",
     "start_time": "2019-03-20T09:36:06.253350Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'embedding_input_dim': 203,\n",
       " 'filter_unit': <mzcn.preprocessors.units.frequency_filter.FrequencyFilter at 0x20fae9cdcc0>,\n",
       " 'vocab_size': 203,\n",
       " 'vocab_unit': <mzcn.preprocessors.units.vocabulary.Vocabulary at 0x20fbc5a5b00>}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "preprocessor.context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=100)\n",
    "# term_index = preprocessor.context['vocab_unit'].state['term_index']\n",
    "# embedding_matrix = glove_embedding.build_matrix(term_index)\n",
    "# l2_norm = np.sqrt((embedding_matrix * embedding_matrix).sum(axis=1))\n",
    "# embedding_matrix = embedding_matrix / l2_norm[:, np.newaxis]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='pair',\n",
    "    num_dup=2,\n",
    "    num_neg=1\n",
    ")\n",
    "devset = mz.dataloader.Dataset(\n",
    "    data_pack=dev_pack_processed\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "padding_callback = mz.models.KNRM.get_default_padding_callback()\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "    stage='train',\n",
    "    callback=padding_callback,\n",
    ")\n",
    "devloader = mz.dataloader.DataLoader(\n",
    "    dataset=devset,\n",
    "    stage='dev',\n",
    "    callback=padding_callback,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.413530Z",
     "start_time": "2019-03-20T09:36:06.267256Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "KNRM(\n",
      "  (embedding): Embedding(203, 100, padding_idx=0)\n",
      "  (kernels): ModuleList(\n",
      "    (0): GaussianKernel()\n",
      "    (1): GaussianKernel()\n",
      "    (2): GaussianKernel()\n",
      "    (3): GaussianKernel()\n",
      "    (4): GaussianKernel()\n",
      "    (5): GaussianKernel()\n",
      "    (6): GaussianKernel()\n",
      "    (7): GaussianKernel()\n",
      "    (8): GaussianKernel()\n",
      "    (9): GaussianKernel()\n",
      "    (10): GaussianKernel()\n",
      "    (11): GaussianKernel()\n",
      "    (12): GaussianKernel()\n",
      "    (13): GaussianKernel()\n",
      "    (14): GaussianKernel()\n",
      "    (15): GaussianKernel()\n",
      "    (16): GaussianKernel()\n",
      "    (17): GaussianKernel()\n",
      "    (18): GaussianKernel()\n",
      "    (19): GaussianKernel()\n",
      "    (20): GaussianKernel()\n",
      "  )\n",
      "  (out): Linear(in_features=21, out_features=1, bias=True)\n",
      ")\n",
      "Trainable params:  20322\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.KNRM()\n",
    "\n",
    "model.params['task'] = ranking_task\n",
    "# model.params['embedding'] = embedding_matrix #这里是当加载glove等模型时取消该行注释\n",
    "#设置embedding系数\n",
    "model.params[\"embedding_output_dim\"]=100\n",
    "model.params[\"embedding_input_dim\"]=preprocessor.context[\"embedding_input_dim\"]\n",
    "model.params['kernel_num'] = 21\n",
    "model.params['sigma'] = 0.1\n",
    "model.params['exact_sigma'] = 0.001\n",
    "\n",
    "model.build()\n",
    "\n",
    "print(model)\n",
    "print('Trainable params: ', sum(p.numel() for p in model.parameters() if p.requires_grad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:36:06.422264Z",
     "start_time": "2019-03-20T09:36:06.415605Z"
    }
   },
   "outputs": [],
   "source": [
    "optimizer = torch.optim.Adadelta(model.parameters())\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=devloader,\n",
    "    validate_interval=None,\n",
    "    epochs=10\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-03-20T09:37:59.341616Z",
     "start_time": "2019-03-20T09:36:06.425086Z"
    }
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8766c16aec854262b0275b0d681f6bbc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1 Loss-1.166]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "eb2898706d814e2cbc68d20717dd9915",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-2 Loss-1.126]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6c093e03c52d4c0f8a77d72f94136601",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-3 Loss-1.087]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7ea21331d8114dc8ae880d09b44e9e5c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-4 Loss-1.049]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1930fb5bdb2a4afc9080a5d485dd4b4b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\r",
      "[Iter-5 Loss-1.013]:\n",
      "\r",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d44e67cecc53447781c0ec751bf8c28e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\r",
      "[Iter-6 Loss-0.978]:\n",
      "\r",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6b9af921f91e44ff986e9dc45e2c4a48",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\r",
      "[Iter-7 Loss-0.944]:\n",
      "\r",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "09c10ceafbb54d4e9d0614049fea563a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\r",
      "[Iter-8 Loss-0.911]:\n",
      "\r",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5c324eb9ff004d159957b1e12edd46b9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-9 Loss-0.878]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "57612ef71c5542f2ace124a30784cbb2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-10 Loss-0.847]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2143 - normalized_discounted_cumulative_gain@5(0.0): 0.2143 - mean_average_precision(0.0): 0.2143\n",
      "\n",
      "Cost time: 3.901357412338257s\n"
     ]
    }
   ],
   "source": [
    "trainer.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  },
  "toc": {
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": "block",
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
